﻿using FastCloud.Base.Desgin;
using FastORM.Applicaiton;
using FastORM.Enum;
using FastUtil.Config;
using FastUtil.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

namespace FastCloud.Base.Config
{
    public class CloudUtil
    {
        private static CommonDao CommonDao = new CommonDao(DataBaseClass.MySql, CloudUtil.GetBaseConnectString());
        private static IWebHostEnvironment Env;

        public static void SetEnviroment(IWebHostEnvironment EnvParam)
        {
            Env = EnvParam;
        }

        public static string GetContentPath()
        {
            return Env.ContentRootPath;
        }

        public static string GetAttachUploadPath(string Group)
        {
            var path = CloudUtil.GetContentPath() + "/" + AppConfigUtil.Configuration["Attach:AttachUploadPath"] + "/";
            if (!string.IsNullOrEmpty(Group))
            {
                path += "/" + Group;
            }
            path += "/" + DateTime.Now.ToString("yyyy-MM-dd");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }


        public static string GetBaseConnectString()
        {
            return AppConfigUtil.Configuration["ConnectionStrings:Cloud_ConnectionString"];
        }
        public static string GetRootPath()
        {
            //协议
            string Scheme = CloudContext.Current.Request.Scheme;
            //域名
            string Host = CloudContext.Current.Request.Host.Value;
            //工程名
            string ApplicationPath = CloudContext.Current.Request.PathBase;
            string RootPath = string.Empty;
            RootPath = Scheme + "://" + Host + ApplicationPath + "/";
            return RootPath;
        }
        public static string GetClientIP()
        {
            return CloudContext.Current.Connection.RemoteIpAddress.ToString();
        }
        public static int GetRedisCacheDBNum()
        {
            return 10;
        }
        public static List<Assembly> GetFrameworkAssemblys()
        {
            var list = new List<Assembly>();
            var deps = DependencyContext.Default;
            var libs = deps.CompileLibraries;
            foreach (var lib in libs)
            {
                if (!lib.Serviceable && lib.Type != "package" && lib.Name.StartsWith("FastCloud"))
                {
                    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
                    list.Add(assembly);
                }
            }
            return list;
        }
        public static string GetFormParam(string ParamName)
        {
            StringValues ParamValues;
            CloudContext.Current.Request.Form.TryGetValue(ParamName, out ParamValues);
            if (ParamValues.Count > 0)
            {
                return ParamValues[0];
            }
            else
            {
                return null;
            }
        }
        public static List<TreeNode> BuildTree(List<TreeNode> AllTreeNode)
        {
            List<TreeNode> TopNodeList = CopyUtil.CopyList<TreeNode>(AllTreeNode.FindAll((TreeNode node) => node.IsTop));
            foreach (TreeNode item in TopNodeList)
            {
                BuildSub(AllTreeNode, item);
            }
            return TopNodeList;
        }
        public static List<TreeNode> BuildGroupTree(List<TreeNode> AllTreeNode)
        {
            List<TreeNode> TopNodeList = CopyUtil.CopyList<TreeNode>(AllTreeNode.FindAll((TreeNode node) => node.IsTop));
            foreach (TreeNode item in TopNodeList)
            {
                BuildSub(AllTreeNode, item);
            }
            foreach (TreeNode item in TopNodeList)
            {
                item.ID = "Top";
            }
            return TopNodeList;
        }
        public static void BuildSub(List<TreeNode> AllTreeNode, TreeNode NowNode)
        {
            List<TreeNode> ChildNodeList = CopyUtil.CopyList<TreeNode>(AllTreeNode.FindAll((TreeNode node) => node.PID == NowNode.ID));
            if (ChildNodeList.Count > 0)
            {
                NowNode.IsParent = true;
            }
            foreach (TreeNode item in ChildNodeList)
            {
                BuildSub(AllTreeNode, item);
                NowNode.AddChildNode(item);
            }
        }
        public static string CreateTableFieldCodeValue(string TableName, string KeyFieldName, string CodeFieldName, string ParentGuidName, string ParentGuid)
        {
            string Code = string.Empty;
            if (ParentGuid == "Top")
            {
                string SQL = string.Format("select max({0}) from {1} where {2}='Top'", CodeFieldName, TableName, ParentGuidName);
                string RecordCode = CommonDao.ExecuteToString(SQL);
                if (string.IsNullOrEmpty(RecordCode))
                {
                    Code = "1000";
                }
                else
                {
                    Code = (Convert.ToInt64(RecordCode) + 1).ToString();
                }
            }
            else
            {
                CommonRow record = new CommonRow(TableName, KeyFieldName, ParentGuid, DataBaseClass.MySql, CloudUtil.GetBaseConnectString());
                string ParentCode = Convert.ToString(record[CodeFieldName]);
                string SQL = string.Format("select max({0}) from {1} where LENGTH({0})={2} and {0} like '{3}%'", CodeFieldName, TableName, ParentCode.Length + 4, ParentCode);
                string RecordCode = CommonDao.ExecuteToString(SQL);
                if (string.IsNullOrEmpty(RecordCode))
                {
                    Code = ParentCode + "1000";
                }
                else
                {
                    Code = (Convert.ToInt64(RecordCode) + 1).ToString();
                }

            }
            return Code;
        }
    }
}
